<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
const activeName = ref('first')
const userIdTemp = ref()
const isComplain = ref(false)
// 评论评分（1-5分）
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])
const isGoComment = ref(false)

const addUserCommentForm = ref({
  orderid: 1,
  review: '',
  point: 3,
  image: ''
})
const complainForm = ref({
  orderid: '1',
  complain: '',
  image: ''
})
// 上传评论图片
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
const imageUrl = ref('')
// 获取订单列表（已完成）
const filteredOrderList = ref([
  {
    orderid: 4,
    userid: 3,
    reviewid: null,
    restaurantid: '刷新一下',
    complainid: null,
    price: 100.0,
    createtime: '',
    state: 1,
    way: 1,
    orders: null
  },
  {
    orderid: 5,
    userid: 3,
    reviewid: 2,
    restaurantid: '刷新一下',
    complainid: null,
    price: 100.0,
    createtime: '',
    state: 3,
    way: 0,
    orders: 1
  },
  {
    orderid: 6,
    userid: 3,
    reviewid: null,
    restaurantid: '刷新一下',
    complainid: 3,
    price: 100.0,
    createtime: '',
    state: 4,
    way: 1,
    orders: null
  }
])
const filteredOrderListRefunded = ref([
  {
    orderid: 5,
    userid: 3,
    reviewid: null,
    restaurantid: '刷新一下',
    complainid: null,
    price: 200.0,
    createtime: '2024-04-28 17:39:28',
    state: 0,
    way: 1,
    orders: null
  }
])
// 查看订单详情
const detailForm = ref([
  {
    orderdetailid: 14,
    orderid: 1,
    foodid: 4,
    image: '',
    price: 2.0,
    number: 2
  }
])
const isViewOrderDetails = ref(false)

// 获取用户信息（用户ID）
const getUserInfo = async () => {
  axios({
    method: 'get',
    url: 'http://localhost:8080/user/userInfo',
    headers: {
      'Content-Type': 'application/octet-stream',
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      userIdTemp.value = res.data.data.userid
      console.log('获取用户信息111', res.data.data.userid)
    },
    (err) => {
      ElMessage.error('获取用户信息失败,请刷新网页')
    }
  )
}
getUserInfo()

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log('切换了')
}
//获取用户订单数据,已完成
const getOrderList0 = () => {
  axios({
    method: 'get',
    url: 'http://localhost:8080/order/getuserorder0',
    headers: {
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      filteredOrderList.value = res.data.data

      console.log('订单数据已完成获取用户id2222', res.data.data[0].userid)
    },
    (err) => {
      ElMessage.error('订单已经完成获取用户信息失败')
    }
  )
}
getOrderList0()

// 获取用户待审核订单
const pendingOrder = ref([
  {
    orderid: 7,
    userid: 1,
    reviewid: null,
    restaurantid: '老兵烧烤',
    complainid: null,
    price: 100.0,
    createtime: '2024-04-29 21:31:49',
    state: 0,
    way: 1,
    orders: null
  }
])
function getPendingOrder() {
  axios({
    method: 'get',
    url: 'http://localhost:8080/order/getuserorder2',
    headers: {
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      pendingOrder.value = res.data.data
      console.log('获取待审核订单')
      console.log(res.data.data)
    },
    (err) => {
      console.log(err)
      ElMessage.error('获取待审核订单失败失败')
    }
  )
}
getPendingOrder()
//获取用户订单数据,已退款
const getOrderList1 = () => {
  filteredOrderList
  axios({
    method: 'get',
    url: 'http://localhost:8080/order/getuserorder1',
    headers: {
      // "Content-Type": "application/octet-stream",
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      filteredOrderListRefunded.value = res.data.data
    },
    (err) => {
      ElMessage.error('退款，获取用户信息失败')
    }
  )
}
getOrderList1()

function isPackFood(row: any, column: any) {
  if (row.way === 1) {
    return '打包'
  } else {
    return '堂食'
  }
}

// 查看订单详情
const tempRestaurantName = ref('')
function viewOrderDetails(row: any) {
  const id = row.orderid
  tempRestaurantName.value = row.restaurantid
  isViewOrderDetails.value = true
  axios({
    method: 'post',
    url: 'http://localhost:8080/order/getuserorderdetail',
    params: {
      id: id
    },
    headers: {
      'Content-Type': 'application/json',
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      detailForm.value = res.data.data
    },
    (err) => {
      console.log(err)
      ElMessage.error('查看订单详情失败,请刷新页面')
    }
  )
}

// 用户添加评论
let OrderIdTemp = ref()
function getCommentOrderId(row: any) {
  OrderIdTemp.value = row.orderid
  isGoComment.value = true
  addUserCommentForm.value.orderid = OrderIdTemp.value
}
// 增加啊评论
function addComment() {
  isGoComment.value = false
  axios({
    method: 'post',
    url: 'http://localhost:8080/review/addreview',
    data: {
      orderid: addUserCommentForm.value.orderid,
      review: addUserCommentForm.value.review,
      point: addUserCommentForm.value.point,
      image: addUserCommentForm.value.image
    },
    headers: {
      'Content-Type': 'application/json',
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      ElMessage.success('成功发表评论！')
      getOrderList0()
    },
    (err) => {
      ElMessage.error('发表评论失败!请刷新后在重新发表')
    }
  )
}

// 上传评论图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  addUserCommentForm.value.image = response.data

  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 用户投诉

// 获取用户投诉ID
function getComplainOrderId(row: any) {
  complainForm.value.orderid = row.orderid

  isComplain.value = true
}
// 增加投诉
function addComplain() {
  isComplain.value = false
  axios({
    method: 'post',
    url: 'http://localhost:8080/complain/addcomplain',
    data: {
      orderid: complainForm.value.orderid,
      complain: complainForm.value.complain,
      image: complainForm.value.image
    },
    headers: {
      'Content-Type': 'application/json',
      Authorization: window.localStorage.getItem('Usertoken')
    }
  }).then(
    (res) => {
      ElMessage.success('投诉成功,等待管理员审核')
    },
    (err) => {
      ElMessage.error('投诉发表失败,请刷新后再试！')
    }
  )
}
// 上传投诉图片
const handleComplainAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log('后回调', response)

  complainForm.value.image = response.data
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeComplainAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是JPG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 8) {
    ElMessage.error('图片不能超过8MB!')
    return false
  }
  return true
}

// 获取用户投诉信息
function getComplaint() {
  axios({
    method: 'post',
    url: 'http://localhost:8080/complain/getallbyuserid',
    headers: {
      'Content-Type': 'application/octet-stream',
      Authorization: window.localStorage.getItem('Usertoken')
    },
    params: {
      userid: userIdTemp.value
    }
  }).then(
    (res) => {
      console.log('获取用户投诉信息成功555', userIdTemp.value)
      // console.log("获取用户投诉信息成功");
      console.log(res.data.data)
      myComplainForm.value = res.data.data
    },
    (err) => {
      ElMessage.error('获取商家信息失败,请刷新网页')
    }
  )
}
setTimeout(() => {
  getComplaint()
}, 2000)
const myComplainForm = ref([
  {
    complainid: null,
    orderid: null,
    complain: null,
    image: null,
    reply: null,
    createtime: null,
    supplement: null,
    state: null
  }
])
// 查看投诉详情
</script>

<template>
  <div class="order-container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="已完成订单" name="first">
        <el-table :data="filteredOrderList" height="100%" style="width: 100%">
          <el-table-column align="center" prop="orderid" label="订单号" width="90" />
          <el-table-column align="center" prop="restaurantid" label="餐厅名称" width="120" />
          <el-table-column align="center" prop="price" label="付款金额" width="80" />
          <el-table-column align="center" prop="createtime" label="下单时间" width="180" />
          <!-- <el-table-column align="center" prop="state" label="状态" width="40" /> -->
          <el-table-column
            align="center"
            prop="way"
            label="就餐方式"
            :formatter="isPackFood"
          ></el-table-column>
          <el-table-column align="center" prop="way" label="操作">
            <template #default="{ row }">
              <el-button plain @click="viewOrderDetails(row)">查看详情</el-button>
              <!-- <el-button plain>退款</el-button> -->
            </template>
          </el-table-column>
          <el-table-column align="center" prop="reviewid" label="评论状态" width="120">
            <template #default="{ row }">
              <el-tag
                type="danger"
                v-if="row.reviewid == null"
                @click="getCommentOrderId(row)"
                style="cursor: pointer"
                >未评论(点击评论)
              </el-tag>
              <el-tag type="success" v-else>已评论</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="complainid" label="投诉状态" width="120">
            <template #default="{ row }">
              <el-tag
                type="primary"
                v-if="row.complainid == null"
                @click="getComplainOrderId(row)"
                style="cursor: pointer"
                >未投诉</el-tag
              >
              <el-tag type="warning" v-else>已投诉</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="待审核订单" name="second">
        <el-table :data="pendingOrder" height="100%" style="width: 100%">
          <el-table-column align="center" prop="orderid" label="订单号" width="90" />
          <el-table-column align="center" prop="restaurantid" label="餐厅名称" width="120" />
          <el-table-column align="center" prop="price" label="付款金额" width="80" />
          <el-table-column align="center" prop="createtime" label="下单时间" width="180" />
          <!-- <el-table-column align="center" prop="state" label="状态" width="40" /> -->
          <el-table-column
            align="center"
            prop="way"
            label="就餐方式"
            :formatter="isPackFood"
          ></el-table-column>
          <el-table-column align="center" prop="way" label="操作">
            <template #default="{ row }">
              <el-button plain @click="viewOrderDetails(row)">查看详情</el-button>
              <!-- <el-button plain>退款</el-button> -->
            </template>
          </el-table-column>
          <el-table-column align="center" prop="reviewid" label="评论状态" width="120">
            <template #default="{ row }">
              <el-tag type="danger" v-if="row.reviewid == null" @click="getCommentOrderId(row)"
                >未评论(点击评论)
              </el-tag>
              <el-tag type="success" v-else>已评论</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="complainid" label="投诉状态" width="120">
            <template #default="{ row }">
              <el-tag type="primary" v-if="row.complainid == null" @click="getComplainOrderId(row)"
                >未投诉</el-tag
              >
              <el-tag type="warning" v-else>已投诉</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="已退款订单" name="third">
        <el-table :data="filteredOrderListRefunded" height="250" style="width: 100%">
          <el-table-column align="center" label="订单号" width="90" type="index" />
          <el-table-column align="center" prop="restaurantid" label="餐厅名称" width="120" />
          <el-table-column align="center" prop="price" label="付款金额" width="120" />
          <el-table-column align="center" prop="createtime" label="下单时间" width="180" />
          <el-table-column align="center" prop="state" label="状态" width="180" />
          <el-table-column
            align="center"
            prop="way"
            label="就餐方式"
            width="200"
            :formatter="isPackFood"
          ></el-table-column>
          <el-table-column align="center" prop="way" width="150" label="操作">
            <template #default="{ row }">
              <el-button plain @click="viewOrderDetails(row)">查看详情</el-button>
              <!-- <el-button plain>退款</el-button> -->
            </template>
          </el-table-column>
          <el-table-column align="center" prop="reviewid" label="评论状态" width="120">
            <template #default="{ row }">
              <el-tag type="danger" v-if="row.reviewid == null" @click="getCommentOrderId(row)"
                >未评论(点击评论)
              </el-tag>
              <el-tag type="success" v-else>已评论</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="complainid" label="投诉状态" width="120">
            <template #default="{ row }">
              <el-tag type="primary" v-if="row.complainid == null" @click="getComplainOrderId(row)"
                >未投诉</el-tag
              >
              <el-tag type="warning" v-else>已投诉</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="我的投诉" name="fourth">
        <el-table :data="myComplainForm" :border="false" style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div style="margin-left: 88px">
                <p>投诉内容：{{ props.row.complain }}</p>
                <el-divider />
                <p>商家回复：{{ props.row.reply }}</p>
                <el-divider />
                <p>赔偿金额：{{ props.row.supplement }}</p>
                <el-divider />
                <el-descriptions title="投诉图片" :column="1" direction="horizontal">
                  <!-- <el-descriptions-item label="投诉内容：">{{ props.row.complain }}<el-divider /></el-descriptions-item>
                  <el-descriptions-item label="商家回复：">{{ props.row.reply }}  <el-divider /></el-descriptions-item>
                  <el-descriptions-item label="赔偿金额：">{{ props.row.supplement }}<el-divider /></el-descriptions-item> -->
                  <el-descriptions-item>
                    <div>
                      <el-image style="width: 180px; height: 180px" :src="props.row.image" />
                    </div>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            width="120"
            label="投诉ID"
            prop="complainid"
            type="index"
          />
          <el-table-column align="center" width="120" label="订单ID" prop="orderid" />
          <el-table-column align="center" width="200" label="发起时间" prop="createtime" />
          <el-table-column align="center" width="150" label="状态" prop="state">
            <template #default="{ row }">
              <el-tag size="small" type="info" v-show="row.state == 0">管理员审核中...</el-tag>
              <el-tag size="small" type="warning" v-show="row.state == 1">商家审核中...</el-tag>
              <el-tag size="small" type="danger" v-show="row.state == 2">管理员审核未通过</el-tag>
              <el-tag size="small" type="success" v-show="row.state == 3">商家审核已通过</el-tag>
              <el-tag size="small" type="danger" v-show="row.state == 4">商家审核未通过</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200" label="操作" prop="createtime">
            <template #default="{ row }">
              <el-button plain @click="viewOrderDetails(row)">查看详情</el-button>
              <!-- <el-button plain>退款</el-button> -->
            </template> </el-table-column
          >>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 查看订单详情 -->
    <el-dialog
      v-model="isViewOrderDetails"
      title="订单详情"
      width="40%"
      style="border-radius: 20px"
    >
      <el-table :data="detailForm">
        <!-- <el-table-column align="center" property="orderdetailid" label="订单详情编号" width="120" /> -->
        <el-table-column align="center" property="image" label="餐厅名称" width="80">{{
          tempRestaurantName
        }}</el-table-column>
        <el-table-column align="center" property="image" label="图片" width="80">
          <!-- <el-image style="width: 100px; height: 100px" src="image"  /> -->
          <template #default="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.image" />
          </template>
        </el-table-column>
        <el-table-column align="center" property="foodid" label="菜品名称" width="80" />
        <el-table-column align="center" property="price" label="单价" width="60" />
        <el-table-column align="center" property="number" label="数量" width="80" />
        <el-table-column align="center" property="number" label="总价" width="80">
          <template #default="{ row }">
            {{ row.price * row.number }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="操作" width="200">
          <template #default="{ row }">
            <el-button plain @click="getCommentOrderId(row)">去评论</el-button>
            <el-button plain @click="getComplainOrderId(row)">我要投诉</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isViewOrderDetails = false">返回</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 发表评论 -->
    <el-dialog v-model="isGoComment" title="发表评论" width="60%">
      <el-table :data="detailForm">
        <el-table-column align="center" property="orderdetailid" label="订单详情编号" width="120" />
        <el-table-column align="center" property="orderid" label="订单号" width="80" type="index" />
        <el-table-column align="center" property="foodid" label="菜品名称" width="80" />
        <el-table-column align="center" property="price" label="总价" width="60" />
        <el-table-column align="center" property="number" label="数量" width="60" />
      </el-table>
      <div style="margin: 40px 0"></div>
      <el-form
        label-position="left"
        label-width="auto"
        :model="addUserCommentForm"
        style="max-width: 600px"
      >
        <el-form-item label="评论">
          <el-input
            v-model="addUserCommentForm.review"
            maxlength="50"
            placeholder="写一些评价体验吧!"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/data/image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            size="large"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate v-model="addUserCommentForm.point" :colors="colors" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isGoComment = false">返回</el-button>
          <el-button @click="addComment">发表评论</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 投诉 -->
    <el-dialog v-model="isComplain" title="投诉" width="60%">
      <el-table :data="detailForm">
        <el-table-column align="center" property="orderdetailid" label="图片" width="120">
          <template #default="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.image" />
          </template>
        </el-table-column>
        <el-table-column align="center" property="orderid" label="订单号" width="80" />
        <el-table-column align="center" property="foodid" label="菜品名称" width="80" />
        <el-table-column align="center" property="price" label="总价" width="60" />
        <el-table-column align="center" property="number" label="数量" width="60" />
      </el-table>
      <div style="margin: 40px 0"></div>
      <el-form
        label-position="left"
        label-width="auto"
        :model="complainForm"
        style="max-width: 600px"
      >
        <el-form-item label="投诉内容">
          <el-input
            v-model="complainForm.complain"
            maxlength="50"
            placeholder="请输入投诉内容"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="投诉图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/data/image"
            :show-file-list="false"
            :on-success="handleComplainAvatarSuccess"
            :before-upload="beforeComplainAvatarUpload"
            size="large"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isComplain = false">返回</el-button>
          <el-button @click="addComplain">发表投诉</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 30px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 评分
.demo-rate-block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
}

.demo-rate-block:last-child {
  border-right: none;
}

.demo-rate-block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

// 评分结束
</style>
<!-- 图片 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 170px;
  height: 120px;
  text-align: center;
}
</style>
